import React, { createContext, useContext, ReactNode } from 'react';
import { message } from 'antd';

interface ToastMessage {
  type: 'success' | 'error';
  text: string;
}

interface ToastContextType {
  showToast: (message: ToastMessage) => void;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

export const useToast = () => {
  const context = useContext(ToastContext);
  if (!context) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  return context;
};

interface ToastProviderProps {
  children: ReactNode;
}

export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
  const [messageApi, contextHolder] = message.useMessage();

  const showToast = (toastMessage: ToastMessage) => {
    if (toastMessage.type === 'success') {
      messageApi.success({
        content: toastMessage.text,
        duration: 3,
        style: {
          marginTop: '16px',
        },
      });
    } else {
      messageApi.error({
        content: toastMessage.text,
        duration: 3,
        style: {
          marginTop: '16px',
        },
      });
    }
  };

  return (
    <ToastContext.Provider value={{ showToast }}>
      {contextHolder}
      {children}
    </ToastContext.Provider>
  );
};